package com.csx.ops.service.node;

import com.csx.ops.dao.ConfigParse;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.yh.csx.bsf.core.db.DbConn;
import com.yh.csx.bsf.core.util.StringUtils;
import lombok.*;

import java.util.List;

@XStreamAlias("SqlNode")
public class SqlNode extends ConfigNode {
    @Getter @Setter
    @XStreamAlias("Db")
    private String db;
    @Getter @Setter
    @XStreamAlias("Sql")
    private String sql;

    @Override
    public void exec(){
        //执行sql前对sql中的字符窜特殊处理
        sql=sql.replaceAll("\r|\n", "");
        printParam(db,sql);
        var dbInfo = new ConfigParse().getDatabaseList(null).get(db);
        if(dbInfo == null)
            throw new StateException("数据库信息未配置:"+ StringUtils.nullToEmpty(db));
        //按逗号分隔语句
        String[] sqlList=sql.split(";");
        if(sqlList.length==0){
            throw new StateException("没有可执行的sql语句");
        }
        try{
            writeLog("sql执行开始");
            try(var conn = new DbConn(dbInfo.get("ip"),dbInfo.get("user"),dbInfo.get("password"),"com.mysql.cj.jdbc.Driver")){
                conn.beginTransaction(0);
                for(String exeSql:sqlList) {
                    conn.executeSql(exeSql, null);
                }
                conn.commit();
            }
            writeLog("sql执行完毕");
        }
        catch (Exception e){
            throw new StateException("sql执行失败:"+StringUtils.subString3(sql,200),e);
        }
        return;
    }

    //从子节点设置对应的状态机
    public void setEngine(StateEngine engine){
        super.setEngine(engine);
    }
}
